package com.hulk.limitb;



import com.hulk.limitb.annotation.EnableLimitbConfig;

import com.hulk.limitb.util.LimitbKeyParser;
import com.hulk.limitb.util.SpringContextHolder;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 *  configuration
 *
 * @author hulk
 */
@Configuration
@ConditionalOnBean(annotation = EnableLimitbConfig.class)
public class LimitbAutoConfiguration {

   @Configuration
   @ConditionalOnClass(RedisTemplate.class)
   protected static class RedisConfig{

      private RedisConnectionFactory redisConnectionFactory;

      public RedisConfig(RedisConnectionFactory redisConnectionFactory){
         this.redisConnectionFactory=redisConnectionFactory;
      }

      @Bean(value = "limitbRedisTemplate")
      public RedisTemplate<String, Object> limitbRedisTemplate() {
         RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
         redisTemplate.setKeySerializer(new StringRedisSerializer());
         redisTemplate.setHashKeySerializer(new StringRedisSerializer());
         redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
         redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
         redisTemplate.setConnectionFactory(redisConnectionFactory);
         return redisTemplate;
      }
   }

   @Bean
   public LimitbKeyParser limitbKeyParser(){
      LimitbKeyParser provider = new LimitbKeyParser();
      return  provider;
   }

   @Bean
   public LimitbInterceptor limitbInterceptor (LimitbKeyParser limitbKeyParser){
      LimitbInterceptor interceptor = new LimitbInterceptor(limitbKeyParser);
      return interceptor;
   }

   @Bean
   public SpringContextHolder springContextHolder (){
      SpringContextHolder springContextHolder = new SpringContextHolder();
      return  springContextHolder;
   }


}
